package com.suxin.plugin.intergration.manager.repository;

import java.io.File;
import java.io.FileFilter;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * @author Tang
 * @classname BasePluginRepository
 * @description [  ]
 * @date 2022/7/3 20:22
 */
public class BasePluginRepository implements PluginRepository {

    protected final Path pluginRoot;

    protected FileFilter filter;

    protected Comparator<File> comparator;

    public BasePluginRepository(Path pluginRoot) {
        this(pluginRoot, null);
    }

    public BasePluginRepository(Path pluginRoot, FileFilter filter) {
        this.pluginRoot = pluginRoot;
        this.filter = filter;

        this.comparator = (o1, o2) -> (int) (o1.lastModified() - o2.lastModified());
    }

    public void setFilter(FileFilter filter) {
        this.filter = filter;
    }

    public void setComparator(Comparator<File> comparator) {
        this.comparator = comparator;
    }

    @Override
    public List<Path> getPluginPaths() {
        File[] files = pluginRoot.toFile().listFiles(filter);
        if (comparator != null) {
            Arrays.sort(files, comparator);
        }
        List<Path> paths = new ArrayList<>(files.length);
        for (File file : files) {
            paths.add(file.toPath());
        }
        return paths;
    }

    @Override
    public boolean deletePluginPath(Path pluginPath) {
        if (!filter.accept(pluginPath.toFile())) {
            return false;
        }
        return pluginPath.toFile().delete();
    }
}